package org.yeruyi.common.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import org.yeruyi.common.RoyLibBuildConfig;

import java.util.ArrayList;
import java.util.List;

/**
 * Author:Yeruyi
 * Date:2017/11/24
 * Version:v1.0
 * Scope:
 * 使用方式：直接调用base类即可 {@link RoyBaseActivity#reqGrantedPermission(java.lang.String[])}
 *
 * 2017年11月24日 权限管理框架页面
 */
public class RoyPermissionActivity extends Activity {

    private static final String TAG = "[RoyPermissionActivity]";

    // 外部请求启动key
    public static final int REQ_PERMISSION = 1001;
    // 内部请求授权key
    private static final int REQ_PERMISSION_SELF = 1002;
    // 传递key
    private static final String PERMISSION_KEY = "pm";
    // 外部未授权权限传递key
    public static final String PERMISSION_DENIED_KEY = "de_pm";

    /**
     * 请求申请权限
     *
     * @param activity    窗口
     * @param permissions 待申请权限
     */
    public static void reqCheckPermissionWithRequest(Activity activity, String[] permissions) {
        Intent intent = new Intent(activity, RoyPermissionActivity.class);
        intent.putExtra(PERMISSION_KEY, permissions);
        activity.startActivityForResult(intent, REQ_PERMISSION);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent() == null || !getIntent().hasExtra(PERMISSION_KEY)) {
            throw new RuntimeException("申请权限错误");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        String[] permissions = getIntent().getStringArrayExtra(PERMISSION_KEY);
        if (RoyLibBuildConfig.LOG_DEBUG) {
            Log.d(TAG, "reqCheckPermissionWithRequest: [待检查权限数量]" + permissions.length);
        }
        String[] newPermissions = _checkPermission(permissions);
        if (newPermissions.length == 0) {
            if (RoyLibBuildConfig.LOG_DEBUG) {
                Log.d(TAG, "onResume: [均已授权]");
            }
            setResult(REQ_PERMISSION);
            finish();
            return;
        }
        if (RoyLibBuildConfig.LOG_DEBUG) {
            Log.d(TAG, "reqCheckPermissionWithRequest: [未授权权限数量]" + newPermissions.length);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(newPermissions, REQ_PERMISSION_SELF);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
//        Log.d(TAG, "onRequestPermissionsResult: [requestCode]" + requestCode);
        switch (requestCode) {
            case REQ_PERMISSION_SELF: {
                ArrayList<String> denidePermission = null;
                if (grantResults.length < 0) {
                    if (RoyLibBuildConfig.LOG_DEBUG)
                        Log.e(TAG, "onRequestPermissionsResult: [申请权限时异常退出]");
                    return;
                }
                if (permissions.length != grantResults.length) {
                    Log.e(TAG, "onRequestPermissionsResult: [申请权限回调时数据异常]");
                    return;
                }
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        if (RoyLibBuildConfig.LOG_DEBUG)
                            Log.d(TAG, "onRequestPermissionsResult: [权限]" + permissions[i] + "[已授权]");
                    } else {
                        if (denidePermission == null)
                            denidePermission = new ArrayList<>();
                        denidePermission.add(permissions[i]);
                        Log.e(TAG, "onRequestPermissionsResult: [权限]" + permissions[i] + "[未授权]");
                    }
                }
                if (denidePermission != null && denidePermission.size() != 0) {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putStringArrayList(PERMISSION_DENIED_KEY, denidePermission);
                    intent.putExtras(bundle);
                    setResult(REQ_PERMISSION, intent);
                    finish();
                    return;
                }
                setResult(REQ_PERMISSION);
                finish();
            }
        }
    }

    /**
     * 检查权限授权情况
     *
     * @param permissions 权限
     * @return 未授权权限
     */
    private String[] _checkPermission(String[] permissions) {
        List<String> permissionsDenied = new ArrayList<String>();
        int i = 0;
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(
                    this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsDenied.add(permission);
            }
        }
        return permissionsDenied.toArray(new String[permissionsDenied.size()]);
    }

}
